package com.summer.oauth.center.controller;

import cn.hutool.core.util.StrUtil;
import com.summer.common.model.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/authority")
public class LogoutController {

    @Qualifier("redisTokenStore")
    @Autowired
    private TokenStore tokenStore;

    @RequestMapping("/require")
    public AjaxResult require() {
        return new AjaxResult(false, "需要登录");
    }

    @RequestMapping("/logout")
    public AjaxResult logout(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (StrUtil.isNotBlank(token)) {
            token = token.substring(7);
            OAuth2AccessToken oAuth2AccessToken = tokenStore.readAccessToken(token);
            if (oAuth2AccessToken != null) {
                tokenStore.removeAccessToken(oAuth2AccessToken);
                tokenStore.removeRefreshToken(oAuth2AccessToken.getRefreshToken());
                return new AjaxResult(true);
            }
        }
        return new AjaxResult(false);
    }
}
